package org.jeecg.modules.mes.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.mes.entity.MesPieceRateStandard;
import org.jeecg.modules.mes.entity.MesProductionPlanTask;
import org.jeecg.modules.mes.entity.MesTaskParticipant;
import org.jeecg.modules.mes.service.IMesPieceRateStandardService;
import org.jeecg.modules.mes.service.IMesProductionPlanTaskService;
import org.jeecg.modules.mes.service.IMesTaskParticipantService;
import org.jeecg.modules.mes.vo.TaskClaimVO;
import org.jeecg.modules.mes.vo.TaskProgressUpdateVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 任务参与者管理
 * @Author: jeecg-boot
 * @Date: 2025-08-30
 * @Version: V2.0
 */
@Api(tags="任务参与者管理")
@RestController
@RequestMapping("/mes/taskParticipant")
@Slf4j
public class MesTaskParticipantController extends JeecgController<MesTaskParticipant, IMesTaskParticipantService> {

    @Autowired
    private IMesTaskParticipantService taskParticipantService;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "任务参与者-分页列表查询")
    @ApiOperation(value="任务参与者-分页列表查询", notes="任务参与者-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MesTaskParticipant>> queryPageList(MesTaskParticipant taskParticipant,
                                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                          HttpServletRequest req) {
        QueryWrapper<MesTaskParticipant> queryWrapper = QueryGenerator.initQueryWrapper(taskParticipant, req.getParameterMap());
        Page<MesTaskParticipant> page = new Page<MesTaskParticipant>(pageNo, pageSize);
        IPage<MesTaskParticipant> pageList = taskParticipantService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 员工领取任务
     */
    @AutoLog(value = "员工领取任务")
    @ApiOperation(value="员工领取任务", notes="员工领取任务")
    @PostMapping(value = "/claimTask")
    public Result<Void> claimTask(@RequestBody TaskClaimVO claimVO) {
        boolean result = taskParticipantService.claimTask(
            claimVO.getTaskId(), 
            claimVO.getEmployeeId(), 
            claimVO.getClaimQuantity(),
            claimVO.getParticipationRatio()
        );
        if (result) {
            return Result.OK("领取任务成功");
        } else {
            return Result.error("领取任务失败");
        }
    }

    /**
     * 获取任务的所有参与者
     */
    @AutoLog(value = "获取任务的所有参与者")
    @ApiOperation(value="获取任务的所有参与者", notes="获取任务的所有参与者")
    @GetMapping(value = "/getByTaskId/{taskId}")
    public Result<List<MesTaskParticipant>> getTaskParticipants(@PathVariable("taskId") String taskId) {
        List<MesTaskParticipant> list = taskParticipantService.getTaskParticipants(taskId);
        return Result.OK(list);
    }

    /**
     * 获取员工参与的任务列表
     */
    @AutoLog(value = "获取员工参与的任务列表")
    @ApiOperation(value="获取员工参与的任务列表", notes="获取员工参与的任务列表")
    @GetMapping(value = "/getByEmployeeId/{employeeId}")
    public Result<List<MesTaskParticipant>> getEmployeeParticipations(@PathVariable("employeeId") String employeeId,
                                                                     @RequestParam(value = "status", required = false) Integer status) {
        List<MesTaskParticipant> list = taskParticipantService.getEmployeeParticipations(employeeId, status);
        return Result.OK(list);
    }

    /**
     * 更新参与者完成进度
     */
    @AutoLog(value = "更新参与者完成进度")
    @ApiOperation(value="更新参与者完成进度", notes="更新参与者完成进度")
    @PostMapping(value = "/updateProgress")
    public Result<Void> updateParticipantProgress(@RequestBody TaskProgressUpdateVO updateVO) {
        boolean result = taskParticipantService.updateParticipantProgress(
            updateVO.getParticipantId(),
            updateVO.getCompletedQuantity()
        );
        if (result) {
            return Result.OK("更新进度成功");
        } else {
            return Result.error("更新进度失败");
        }
    }

    /**
     * 完成任务参与
     */
    @AutoLog(value = "完成任务参与")
    @ApiOperation(value="完成任务参与", notes="完成任务参与")
    @PostMapping(value = "/complete")
    public Result<Void> completeParticipation(@RequestParam("participantId") String participantId,
                                             @RequestParam(value = "qualityScore", required = false) BigDecimal qualityScore,
                                             @RequestParam(value = "efficiencyScore", required = false) BigDecimal efficiencyScore) {
        boolean result = taskParticipantService.completeParticipation(participantId, qualityScore, efficiencyScore);
        if (result) {
            return Result.OK("完成任务成功");
        } else {
            return Result.error("完成任务失败");
        }
    }

    /**
     * 开始任务执行
     */
    @AutoLog(value = "开始任务执行")
    @ApiOperation(value="开始任务执行", notes="开始任务执行")
    @PostMapping(value = "/start/{participantId}")
    public Result<Void> startTaskExecution(@PathVariable("participantId") String participantId) {
        boolean result = taskParticipantService.startTaskExecution(participantId);
        if (result) {
            return Result.OK("开始任务成功");
        } else {
            return Result.error("开始任务失败");
        }
    }

    /**
     * 暂停任务执行
     */
    @AutoLog(value = "暂停任务执行")
    @ApiOperation(value="暂停任务执行", notes="暂停任务执行")
    @PostMapping(value = "/pause")
    public Result<Void> pauseTaskExecution(@RequestParam("participantId") String participantId,
                                          @RequestParam(value = "reason", required = false) String reason) {
        boolean result = taskParticipantService.pauseTaskExecution(participantId, reason);
        if (result) {
            return Result.OK("暂停任务成功");
        } else {
            return Result.error("暂停任务失败");
        }
    }

    /**
     * 恢复任务执行
     */
    @AutoLog(value = "恢复任务执行")
    @ApiOperation(value="恢复任务执行", notes="恢复任务执行")
    @PostMapping(value = "/resume/{participantId}")
    public Result<Void> resumeTaskExecution(@PathVariable("participantId") String participantId) {
        boolean result = taskParticipantService.resumeTaskExecution(participantId);
        if (result) {
            return Result.OK("恢复任务成功");
        } else {
            return Result.error("恢复任务失败");
        }
    }

    /**
     * 获取任务的参与者统计信息
     */
    @AutoLog(value = "获取任务的参与者统计信息")
    @ApiOperation(value="获取任务的参与者统计信息", notes="获取任务的参与者统计信息")
    @GetMapping(value = "/getStats/{taskId}")
    public Result<MesTaskParticipant> getTaskParticipantStats(@PathVariable("taskId") String taskId) {
        MesTaskParticipant stats = taskParticipantService.getTaskParticipantStats(taskId);
        return Result.OK(stats);
    }

    /**
     * 检查员工是否已参与该任务
     */
    @AutoLog(value = "检查员工是否已参与该任务")
    @ApiOperation(value="检查员工是否已参与该任务", notes="检查员工是否已参与该任务")
    @GetMapping(value = "/checkParticipation")
    public Result<MesTaskParticipant> checkEmployeeParticipation(@RequestParam("taskId") String taskId,
                                                                @RequestParam("employeeId") String employeeId) {
        MesTaskParticipant participant = taskParticipantService.checkEmployeeParticipation(taskId, employeeId);
        return Result.OK(participant);
    }

    /**
     * 移除任务参与者
     */
    @AutoLog(value = "移除任务参与者")
    @ApiOperation(value="移除任务参与者", notes="移除任务参与者")
    @PostMapping(value = "/removeParticipant/{participantId}")
    public Result<Void> removeParticipant(@PathVariable("participantId") String participantId) {
        boolean result = taskParticipantService.removeParticipant(participantId);
        if (result) {
            return Result.OK("移除参与者成功");
        } else {
            return Result.error("移除参与者失败");
        }
    }

    /**
     * 批量分配任务给多个员工
     */
    @AutoLog(value = "批量分配任务给多个员工")
    @ApiOperation(value="批量分配任务给多个员工", notes="批量分配任务给多个员工")
    @PostMapping(value = "/batchAssign")
    public Result<Void> batchAssignTask(@RequestParam("taskId") String taskId,
                                       @RequestParam("employeeIds") List<String> employeeIds,
                                       @RequestParam("quantities") List<Integer> quantities,
                                       @RequestParam("ratios") List<BigDecimal> ratios) {
        boolean result = taskParticipantService.batchAssignTask(taskId, employeeIds, quantities, ratios);
        if (result) {
            return Result.OK("批量分配任务成功");
        } else {
            return Result.error("批量分配任务失败");
        }
    }

    /**
     * 添加
     */
    @AutoLog(value = "任务参与者-添加")
    @ApiOperation(value="任务参与者-添加", notes="任务参与者-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MesTaskParticipant taskParticipant) {
        taskParticipantService.save(taskParticipant);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     */
    @AutoLog(value = "任务参与者-编辑")
    @ApiOperation(value="任务参与者-编辑", notes="任务参与者-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody MesTaskParticipant taskParticipant) {
        taskParticipantService.updateById(taskParticipant);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "任务参与者-通过id删除")
    @ApiOperation(value="任务参与者-通过id删除", notes="任务参与者-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        taskParticipantService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "任务参与者-批量删除")
    @ApiOperation(value="任务参与者-批量删除", notes="任务参与者-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.taskParticipantService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "任务参与者-通过id查询")
    @ApiOperation(value="任务参与者-通过id查询", notes="任务参与者-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MesTaskParticipant> queryById(@RequestParam(name="id",required=true) String id) {
        MesTaskParticipant taskParticipant = taskParticipantService.getById(id);
        if(taskParticipant==null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(taskParticipant);
    }

    @Autowired
    private IMesProductionPlanTaskService mesProductionPlanTaskService;
    @Autowired
    private IMesPieceRateStandardService mesPieceRateStandardService;
    /**
     * 分页列表查询
     */
    @AutoLog(value = "任务参与者-根据用户ID获取已提交的任务，分页列表查询")
    @ApiOperation(value="任务参与者-根据用户ID获取已提交的任务，分页列表查询", notes="任务参与者-根据用户ID获取已提交的任务，分页列表查询")
    @GetMapping(value = "/listByEmpIdAndSubmitStatus")
    public Result<IPage<MesTaskParticipant>> listByEmpIdAndSubmitStatus(MesTaskParticipant taskParticipant,
                                                           @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                           HttpServletRequest req) {
        QueryWrapper<MesTaskParticipant> queryWrapper = QueryGenerator.initQueryWrapper(taskParticipant, req.getParameterMap());
        Page<MesTaskParticipant> page = new Page<MesTaskParticipant>(pageNo, pageSize);
        IPage<MesTaskParticipant> pageList = taskParticipantService.page(page, queryWrapper);
        List<MesTaskParticipant> resultList = new ArrayList<>();
        //设置任务的产品、订单
        for (MesTaskParticipant participant : pageList.getRecords()) {
            if(participant.getEndTime() != null){
                MesProductionPlanTask task = mesProductionPlanTaskService.getById(participant.getTaskId());
                participant.setProductInfo(task.getProductInfo());
                participant.setOrderNo(task.getOrderNo());
                //计件单价
                MesPieceRateStandard pieceRateStandard = mesPieceRateStandardService.getById(task.getPieceRateStandardId());
                participant.setUnitPrice(pieceRateStandard.getBaseRate());
                participant.setWorkTypeName(task.getWorkTypeName());
                resultList.add( participant);
            }
        }
        pageList.setRecords(resultList);
        return Result.OK(pageList);
    }
}
